package com.sinoglobal.shakeprize.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import okhttp3.Request;

import com.alibaba.fastjson.JSON;
import com.sinoglobal.shakeprize.R;
import com.sinoglobal.shakeprize.adapter.AnimationPageTransformer;
import com.sinoglobal.shakeprize.adapter.ShakeSessionAdapter;
import com.sinoglobal.shakeprize.bean.ResponseShakeSessionList;
import com.sinoglobal.shakeprize.bean.ResponseShakeSessionListItem;
import com.sinoglobal.shakeprize.utils.Contstent;
import com.sinoglobal.shakeprize.utils.FlyUtil;
import com.sinoglobal.shakeprize.utils.ItktLog;
import com.sinoglobal.shakeprize.utils.OKhttpUtil;
import com.sinoglobal.shakeprize.utils.OKhttpUtil.ResponseCallback;
import com.sinoglobal.shakeprize.utils.SPUtil;

/**
 * @author temulu
 * @createdate 2015-8-26下午2:37:44
 * @Description 场次界面
 */
public class ShakeSessionActivity extends FragmentActivity implements
		OnClickListener {
	private static final String TAG = "JPush";
	private static final int MSG_SET_ALIAS = 1001;
	private static final int ORDER_TIME = 0;// 最近场次
	private static final int ORDER_POPULARITY = 1;// 人气最高
	private static final int ORDER_NOTIFY = 3;// 更新viewpager
	private static final int ORDER_FAIL = 4;// json解析失败

	private ImageView shakeTitleLeft;
	private TextView shakeTitleText;
	private ImageView shakeTitleRight;
	private ImageView shakeTitleSort;
	private ViewPager sessionPager;
	private PopupWindow popupWindow;
	private ImageView shakeSessionIndicator;
	private LinearLayout shakeSessionNomal;
	private ShakeSessionAdapter sessionAdapter;
	private String json;
	private ResponseShakeSessionList responseList;
	private List<ResponseShakeSessionListItem> listItems = new ArrayList<ResponseShakeSessionListItem>();
	private long systemTime;
	private ResponseShakeSessionList responseList2;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ORDER_NOTIFY:
				sessionAdapter.setList(responseList2.rs.roundlist,
						responseList2.systime);
				break;
			case ORDER_FAIL:
				Toast.makeText(ShakeSessionActivity.this, "访问网络失败，请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};

	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
		@Override
		public void gotResult(int code, String alias, Set<String> tags) {
			String logs;
			switch (code) {
			case 0:
				logs = "Set tag and alias success";
				Log.i(TAG, logs);
				// 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
				break;
			case 6002:
				logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
				Log.i(TAG, logs);
				// 延迟 60 秒来调用 Handler 设置别名
				handler.sendEmptyMessageDelayed(MSG_SET_ALIAS, 1000 * 60);
				break;
			default:
				logs = "Failed with errorCode = " + code;
				Log.e(TAG, logs);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shake_activity_session);
		initData();
		initView();
	}

	private void initData() {
		json = getIntent().getStringExtra("ShakeSessionList");
		responseList = JSON.parseObject(json, ResponseShakeSessionList.class);
		listItems = responseList.rs.roundlist;
		systemTime = responseList.systime;
	}

	private void initView() {
		findViewById(R.id.shakeTitleBg).setBackgroundResource(
				R.drawable.title_bg);
		shakeTitleLeft = (ImageView) findViewById(R.id.shakeTitleLeft);
		shakeTitleText = (TextView) findViewById(R.id.shakeTitleText);
		shakeTitleRight = (ImageView) findViewById(R.id.shakeTitleRight);
		shakeTitleSort = (ImageView) findViewById(R.id.shakeTitleSort);
		sessionPager = (ViewPager) findViewById(R.id.sessionPager);
		shakeSessionNomal = (LinearLayout) findViewById(R.id.shakeSessionNomal);
		shakeSessionIndicator = (ImageView) findViewById(R.id.shakeSessionIndicator);
		shakeTitleText.setTextColor(getResources().getColor(R.color.white));
		shakeTitleText.setText("最近场次");
		shakeTitleSort.setVisibility(View.VISIBLE);
		shakeTitleLeft.setOnClickListener(this);
		shakeTitleRight.setOnClickListener(this);
		shakeTitleSort.setOnClickListener(this);
		sessionAdapter = new ShakeSessionAdapter(getSupportFragmentManager(),
				listItems, systemTime);
		sessionPager.setPageMargin(-20);
		sessionPager.setAdapter(sessionAdapter);
		sessionPager.setPageTransformer(true, new AnimationPageTransformer());
		LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		for (int i = 0; i < listItems.size(); i++) {
			ImageView imageNomal = new ImageView(this);
			imageNomal.setBackgroundResource(R.drawable.shake_pager_number);
			if (i > 0) {
				linearParams.leftMargin = FlyUtil.dip2px(this, 10);
				imageNomal.setLayoutParams(linearParams);
			}
			shakeSessionNomal.addView(imageNomal);
		}
		pagerIndicator();
		JPushInterface.setAliasAndTags(getApplicationContext(),
				SPUtil.getString(ShakeSessionActivity.this, Contstent.USER_ID), null, mAliasCallback);
	}

	@Override
	public void onClick(View v) {
		if (v.getId()==R.id.shakeTitleLeft) {
			finish();
		} else if (v.getId()==R.id.shakeTitleRight) {
			Intent intent = new Intent(this, ShakeActivity.class);
			intent.putExtra("roundid", responseList.rs.roundid);
			intent.putExtra("size", responseList.rs.roundlist.size());
			FlyUtil.intentForward(this, intent);
		}else if (v.getId()==R.id.shakeTitleSort) {
			showPopWindow();
		}else if (v.getId()==R.id.shakePopText1) {
			shakeTitleText.setText("最近场次");
			orderSession(ORDER_TIME);
			popupWindow.dismiss();
		}else if (v.getId()==R.id.shakePopText2) {
			shakeTitleText.setText("人气最高");
			orderSession(ORDER_POPULARITY);
			popupWindow.dismiss();
		}
	}

	/** 选择场次排序 */
	private void showPopWindow() {
		if (popupWindow == null) {
			View view = View.inflate(this, R.layout.shake_session_pop_layout,
					null);
			TextView shakePopText1 = (TextView) view
					.findViewById(R.id.shakePopText1);
			TextView shakePopText2 = (TextView) view
					.findViewById(R.id.shakePopText2);
			shakePopText1.setOnClickListener(this);
			shakePopText2.setOnClickListener(this);
			popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT, true);
			popupWindow.setOutsideTouchable(true);
			popupWindow
					.setBackgroundDrawable(new BitmapDrawable(getResources()));
		}
		popupWindow.showAsDropDown(shakeTitleSort, FlyUtil.dip2px(this, -50),
				FlyUtil.dip2px(this, -6));

	}

	/** viewpager滑动指示器 */
	private void pagerIndicator() {
		sessionPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageScrolled(int paramInt1, float paramFloat,
					int paramInt2) {
				shakeSessionIndicator.setTranslationX((paramInt1 + paramFloat)
						* (shakeSessionIndicator.getWidth() + FlyUtil.dip2px(
								ShakeSessionActivity.this, 10)));
			}

			@Override
			public void onPageSelected(int paramInt) {

			}

			@Override
			public void onPageScrollStateChanged(int paramInt) {

			}

		});
	}

	/** 返回主页 */
	protected void goHome() {
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		handler.removeCallbacksAndMessages(null);
		sessionPager.getHandler().removeCallbacksAndMessages(null);
	}

	private void orderSession(int orderBy) {
		Map<String, Object> request = new HashMap<String, Object>();
		request.put("userId", SPUtil.getString(ShakeSessionActivity.this, Contstent.USER_ID));
		request.put("productCode", Contstent.PRODUCT_IDENTIFICATION);
		request.put("orderBy", orderBy);
		String url = Contstent.SHAKE_PATH + "yaoyiyao/roundList.do?json="
				+ JSON.toJSONString(request);
		OKhttpUtil.enqueue(url, new ResponseCallback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				Log.e("DispatchIntentHelper", "访问网络失败");
			}

			@Override
			public void onResponse(String json) throws IOException {
				try {
					ItktLog.e("Response:" + json);
					responseList2 = JSON.parseObject(json,
							ResponseShakeSessionList.class);
				} catch (Exception e) {
					handler.sendEmptyMessage(ORDER_FAIL);
					return;
				}
				if (responseList2.rs.roundlist.size() > 0) {
					handler.sendEmptyMessage(ORDER_NOTIFY);
				}
			}
		});
	}

}
